package com.zgis.monitor.util;

import com.zgis.monitor.config.MonitorConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.internet.MimeMessage;
import java.util.Objects;

/**
 * 邮件工具类
 */
@Slf4j
@Component
public class MailUtil
{
    @Value("${spring.mail.username}")
    private       String         from;
    private final JavaMailSender mailSender;

    public MailUtil(JavaMailSender mailSender, JavaMailSender javaMailSender)
    {
        this.mailSender = mailSender;
    }

    /**
     * 发送服务停止告警邮件
     */
    public void sendServiceDownAlarm(String to, String serverIp, MonitorConfig.ServiceConfig service)
    {
        String subject = "[服务告警] " + service.getName() + " 已停止运行";
        String content = String.format(
                "<html><body>" +
                        "<h3>服务停止告警</h3>" +
                        "<p>服务器IP：%s</p>" +
                        "<p>服务ID：%s</p>" +
                        "<p>服务名称：%s</p>" +
                        "<p>服务类型：%s</p>" +
                        "<p>服务端口：%d</p>" +
                        "<p>告警时间：%s</p>" +
                        "<p>请及时排查问题或重启服务！</p>" +
                        "</body></html>",
                serverIp,
                service.getId(),
                service.getName(),
                service.getType(),
                service.getPort(),
                DateTimeUtils.millisToDateTimeStr(System.currentTimeMillis())
        );

        try
        {
            MimeMessage       message = mailSender.createMimeMessage();
            MimeMessageHelper helper  = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(to.split(","));
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            log.info("服务停止告警邮件已发送至：{}，服务：{}@{}", to, service.getId(), serverIp);
        }
        catch (javax.mail.MessagingException e)
        {
            log.error("发送邮件失败，收件人：{}，服务：{}@{}", to, service.getId(), serverIp, e);
        }
    }
}